Number of Connected Components
Question
Given the number of nodes in an undirected graph and a list of its edges, return the number of connected components in that graph.
For example, n = 3, edges = [[5, 3], [3, 1]]
means that there are 3 total nodes, where there's an edge between 5 and 3 as well as an edge between 3 and 1.
You can assume that the value of nodes will range from 0 to num_nodes - 1.
Input: n = 3, edges = [[0, 1], [0, 2]]
Output: 1
All the nodes are connected in some way, therefore there is only one component.
Input: n = 6, edges = [[0, 1], [1, 2], [2, 3], [4, 5]]
Output: 2
There are two components in this case. One containing nodes [0, 1, 2, 3] and the other one containing nodes [4, 5],
Input: n = 8, edges = [[0, 1], [1, 2], [1, 4], [2, 3], [5, 6]]
Output: 3
There are three components in this case. One containing nodes [0, 1, 2, 3, 4], another one containing nodes [5, 6], and the node 7 that's isolated.
Clarify the problem
What are some questions you'd ask an interviewer?
Understand the problem
Take a moment to understand the problem and think of your approach before you start coding.